import blue
import util
import uthread
import uicls
import uiutil
import const
import sys
import uiconst

class EntityBrowserCore(uicls.WindowCore):
    __guid__ = 'uicls.EntityBrowserCore'
    default_windowID = 'entityBrowser'

    def ApplyAttributes(self, attributes):
        super(uicls.EntityBrowserCore, self).ApplyAttributes(attributes)
        self.SetMinSize([100, 200])
        self.SetHeight(200)
        self.SetCaption('Entity Browser')
        self.sr.content.SetPadding(5, 5, 5, 5)
        self.sr.content.searchEntryLabel = uicls.LabelCore(parent=self.sr.content, align=uiconst.TOPLEFT, text='Entity ID:  ')
        self.sr.content.searchEntry = uicls.SinglelineEditCore(parent=self.sr.content, align=uiconst.TOPLEFT, left=(self.sr.content.searchEntryLabel.width + 10), width=200)
        self.sr.content.searchButton = uicls.ButtonCore(parent=self.sr.content, align=uiconst.TOPLEFT, left=((self.sr.content.searchEntry.left + self.sr.content.searchEntry.width) + 20), label='View Entity', func=self.ViewEntityButtonFunc)
        self.sr.content.scroll = uicls.ScrollCore(parent=self.sr.content, top=35)
        self.sr.content.scroll.sr.id = 'monitorscroll'
        self.thread = uthread.new(self.LoadEntitiesThread)



    def LoadEntitiesThread(self):
        while not self.dead:
            self.LoadEntities()
            blue.pyos.synchro.Sleep(1000)




    def LoadEntities(self):
        entityClient = sm.GetService('entityClient')
        scrolllist = []
        for (sceneID, scene,) in entityClient.scenes.iteritems():
            name = self.GetSceneName(sceneID)
            data = {'decoClass': uicls.SE_EntityBrowserGroup,
             'GetSubContent': self.GetSceneListEntries,
             'label': ('%d<t>%s (%s)' % (sceneID,
                       name,
                       len(scene.entities))),
             'id': ('scene', sceneID),
             'state': 'locked',
             'showlen': False,
             'scene': scene}
            scrolllist.append(uicls.ScrollEntryNode(**data))

        self.sr.content.scroll.Load(contentList=scrolllist, headers=['ID',
         'Name',
         'State'])



    def GetSceneName(self, sceneID):
        return 'Scene Name'



    def GetEntityName(self, entity):
        return 'Entity Name'



    def GetSceneListEntries(self, data, *args):
        scene = data['scene']
        scrolllist = []
        for (entityID, entity,) in scene.entities.iteritems():
            name = self.GetEntityName(entity)
            data = {'decoClass': uicls.SE_EntityBrowserEntry,
             'label': ('%s<t>%s<t>%s' % (entityID,
                       name,
                       const.zentity.ENTITY_STATE_NAMES[entity.state])),
             'entityID': entityID,
             'OnDblClick': self.DblClickEntry}
            scrolllist.append(uicls.ScrollEntryNode(**data))

        return scrolllist



    def DblClickEntry(self, entry):
        entityID = util.GetAttrs(entry, 'sr', 'node', 'entityID')
        self.ViewEntity(entityID)



    def ViewEntityButtonFunc(self, buttonObj):
        entID = self.sr.content.searchEntry.GetValue()
        self.ViewEntity(int(entID))



    def ViewEntity(self, entID):
        entity = sm.GetService('entityClient').FindEntityByID(entID)
        uicls.EntityMonitor(parent=uicore.layer.main, entID=entID)




class EntityMonitor(uicls.WindowCore):
    __guid__ = 'uicls.EntityMonitor'
    default_windowID = 'entityMonitor'

    def ApplyAttributes(self, attributes):
        super(uicls.EntityMonitor, self).ApplyAttributes(attributes)
        self.SetMinSize([300, 200])
        self.SetHeight(200)
        self.entityID = attributes.get('entID', 0)
        self.SetCaption(('Entity Monitor for %d' % self.entityID))
        self.entityClient = sm.GetService('entityClient')
        self.sr.content.scroll = uicls.ScrollCore(parent=self.sr.content, padding=(5, 5, 5, 5))
        self.sr.content.scroll.sr.id = 'monitorscroll'
        self.componentNodes = {}
        self.componentDataNodes = {}
        self.thread = uthread.new(self.LoadEntityThread)



    def LoadEntityThread(self):
        while not self.dead:
            self.LoadEntity()
            blue.pyos.synchro.Sleep(250)




    def LoadEntity(self):
        entity = self.entityClient.FindEntityByID(self.entityID)
        if not entity:
            self.SetCaption(('Entity Monitor for %d (NOT FOUND)' % self.entityID))
            self.componentNodes = {}
            self.sr.content.scroll.LoadContent(contentList=self.componentNodes.values())
            return 
        newComponents = entity.components.keys()
        requiresUpdate = False
        for componentName in newComponents:
            if (componentName not in self.componentNodes):
                requiresUpdate = True
                data = {'decoClass': uicls.SE_ListGroupCore,
                 'GetSubContent': self.GetComponentListEntries,
                 'label': componentName,
                 'id': ('component', componentName),
                 'showicon': 'hide',
                 'showlen': False,
                 'componentName': componentName,
                 'state': 'locked'}
                node = uicls.ScrollEntryNode(**data)
                self.componentNodes[componentName] = node
            if (componentName in self.componentDataNodes):
                state = self.entityClient.GetComponentStateByID(self.entityID, componentName)
                if state:
                    for (name, value,) in state.iteritems():
                        label = ('%s<t>%s' % (name, value))
                        if (name in self.componentDataNodes[componentName]):
                            if self.componentDataNodes[componentName][name].panel:
                                self.componentDataNodes[componentName][name].panel.sr.label.SetText(label)


        if requiresUpdate:
            self.sr.content.scroll.LoadContent(contentList=self.componentNodes.values(), headers=['name', 'value'])



    def GetComponentListEntries(self, data, *args):
        componentName = data['componentName']
        self.componentDataNodes[componentName] = {}
        state = self.entityClient.GetComponentStateByID(self.entityID, componentName)
        if state:
            for (name, value,) in state.iteritems():
                data = {'label': ('%s<t>%s' % (name, value))}
                node = uicls.ScrollEntryNode(**data)
                self.componentDataNodes[componentName][name] = node

        return self.componentDataNodes[componentName].values()




class SE_EntityBrowserGroup(uicls.SE_ListGroupCore):
    __guid__ = 'uicls.SE_EntityBrowserGroup'

    def GetMenu(self):
        menu = super(uicls.SE_EntityBrowserGroup, self).GetMenu()
        if not self.sr.node.get('showmenu', True):
            return menu
        else:

            def CopyID(id):
                blue.pyos.SetClipboardData(str(id))


            menu += [('Copy Scene ID',
              CopyID,
              (self.sr.node.get('id', ('', 0))[1]))]
            return menu




class SE_EntityBrowserEntry(uicls.SE_GenericCore):
    __guid__ = 'uicls.SE_EntityBrowserEntry'

    def GetMenu(self):
        menu = []
        if not self.sr.node.get('showmenu', True):
            return menu
        else:

            def CopyID(id):
                blue.pyos.SetClipboardData(str(id))


            menu += [('Copy ID',
              CopyID,
              (self.sr.node.get('entityID', 0)))]
            return menu




